var http = {};
function fetch(params, method) {
    var url = params.url;
    var async = (params.async === undefined) ? true : params.async;
    var data = params.data;
    var dataType = params.dataType || 'json';
    $.ajax({
        url: url,
        type: method,
        async: async,
        // 如果是字符串会多出双引号
        data: data ? JSON.stringify(data) : {},
        dataType: dataType,
        contentType: 'application/json;charset=utf-8',
        success: function (res) {
            if(!res) {
                return;
            }
            if (res.code === 0 || res.success === true) {
                params.success(res.data);
                return;
            }
            if (params.error) {
                params.error(res);
                return;
            }
            if(res.message) {
                alert(res.message);
            }
        },
        error: function (request) {
            if (request.status === 401) {
                var pathname = encodeURIComponent(location.href);

                //尝试cookies自动登录

                window.location.href = common.ctx + "/html/login.html?pathname="+pathname;
                return;
            }
            var res = request.responseJSON || eval('(' + request.responseText + ')');
            if (params.error) {
                params.error(res);
                return;
            }
            if(res && res.message) {
                alert(res.message);
            }
        }
    });
}
http.get = function (params) {
    fetch(params, 'GET');
};
http.post = function (params) {
    fetch(params, 'POST');
};
http.put = function (params) {
    fetch(params, 'PUT');
};
http.del = function (params) {
    fetch(params, 'DELETE');
};

